package com.example.demo.controller

import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.*

@Controller
@RequestMapping("/api")
class DemoController {
    @RequestMapping("/hello")
    @ResponseBody
    fun hello(): String {
        return "Hello World"
    }

    @RequestMapping(value = ["/index", "/main", "/"])
    @ResponseBody
    fun index1(): String {
        return "Hello World"
    }

    @RequestMapping("/get", method = [RequestMethod.GET])
    @ResponseBody
    fun get(): String {
        return "GET请求"
    }

    @RequestMapping("/post", method = [RequestMethod.POST])
    @ResponseBody
    fun post(): String {
        return "POST请求"
    }

    @RequestMapping("/param1")
    @ResponseBody
    fun param1(name: String?): String {
        // 注意：由于方法的参数名是name，所以传入的参数名也应该是name
        // 因为Kotlin的默认数据类型不支持null，如果想要允许这种情况，可以修改name的类型为String?
        return "你的用户名是$name"
    }

    @RequestMapping("/param2", params = ["age", "name"])
    @ResponseBody
    fun param2(name: String, age: Int): String {
        // params 属性要求参数必须存在，否则请求将无法匹配到该方法
        return "你的用户名是$name，年龄是$age"
    }

    @RequestMapping("/param3")
    @ResponseBody
    fun param3(@RequestParam("name", defaultValue = "defaultValue") name: String?): String {
        // 传递参数可以自动传递，也可以通过@RequestParam传递
        return "你的用户名是$name"
    }

    @RequestMapping("/json1", consumes = ["application/json"])
    @ResponseBody
    fun json1(): String {
        // 要求请求数据必须是json格式
        return "主页"
    }

    @RequestMapping("/json2")
    @ResponseBody
    fun json2(@RequestBody usernames: List<String>): String {
        var users = ""
        for (user in usernames) {
            users += user
            users += "\n"
        }
        return users
    }

    @RequestMapping("/path/{name}")
    @ResponseBody
    fun index(@PathVariable("name") username: String): String {
        return "你的用户名是$username"
    }
}

